import {
  computed,
  defineComponent,
  onMounted,
  PropType,
  ref
} from 'vue';
import { BlockModel, VisualEditorConfig } from '@/model/model';
import './index.scss';

export const VisualEditorBlock = defineComponent({
  props: {
    block: {
      type: Object as PropType<BlockModel>
    },
    config: {
      type: Object as PropType<VisualEditorConfig>
    }
  },
  setup(props) {
    const el = ref({} as HTMLDivElement);
    const blockStyles = computed(() => ({
      top: `${props.block?.top}px`,
      left: `${props.block?.left}px`
    }));
    const classes = computed(() => ['visual-editor-block', {
      'visual-editor-block-focus': props.block?.focus
    }]);

    onMounted(() => {
      const { block } = props;
      if (block?.adjustPosition) {
        const { offsetWidth, offsetHeight } = el.value;
        block.left -= offsetWidth / 2;
        block.top -= offsetHeight / 2;
        block.adjustPosition = false;
      }
    });

    return () => {
      const component = props.config?.componentMap[props.block!.componentKey];
      const Render = component?.render();
      return (
        <div class={classes.value} style={blockStyles.value} ref={el}>
          {
            Render
          }
        </div>
      )
    }
  }
});
